package com.ycrlkj.android.modulesbase.libbase.Rxjava;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;


/**
 * 自定义 Rxjava Lifecycle 生命周期绑定类
 *
 * 防内存泄漏(用户刚打开某页面, 正在发送请求时按了返回键, 如果不处理取消网络请求订阅, 会造成内存泄漏)
 *
 * 用法:
 *
 *   DemoApiService.getAll()
 *     .compose(RxLifecycle.bindRxLifecycle(this)) //在 Observable 对象链式调用时加上此行
 *
 */
public class RxLifecycle<T> implements LifecycleObserver, ObservableTransformer<T, T> {

    final CompositeDisposable compositeDisposable = new CompositeDisposable();

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void onDestroy(){
        Log.e("ming", "RxLifecycle 检测到窗口关闭" );

        if(!compositeDisposable.isDisposed()){
            compositeDisposable.dispose();
        }
    }

    @NonNull
    @Override
    public ObservableSource<T> apply(@NonNull Observable<T> upstream) {
        return upstream.doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                compositeDisposable.add(disposable);
            }
        });
    }

    public static <T> RxLifecycle<T> bindRxLifecycle(LifecycleOwner lifecycleOwner){
        RxLifecycle<T> lifecycle = new RxLifecycle<>();
        lifecycleOwner.getLifecycle().addObserver(lifecycle);
        return lifecycle;
    }

}
